<template>
  <div class="three-box"></div>
</template>

<script setup>
import {
  Scene,
  WebGLRenderer,
  OrthographicCamera,
  BoxGeometry,
  MeshBasicMaterial,
  Mesh,
  AxesHelper,
  PointLight,
  AmbientLight,
  SphereGeometry
} from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { onMounted } from "vue";

const renderer = new WebGLRenderer();
const scene = new Scene();

onMounted(() => {
  const dom = document.querySelector(".three-box");
  console.log("dom======>", dom, dom.offsetWidth, dom.offsetHeight);
  renderer.setSize(dom.offsetWidth, dom.offsetHeight);

  dom.appendChild(renderer.domElement);

  const axesHelper = new AxesHelper(500);

  scene.add(axesHelper);

  let width = window.innerWidth; //窗口宽度
  let height = window.innerHeight; //窗口高度
  let k = width / height; //窗口宽高比
  let s = 300; //三维场景显示范围控制系数，系数越大，显示的范围越大
  //创建相机对象
  let camera = new OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
  camera.position.set(200, 300, 200); //设置相机位置
  camera.lookAt(scene.position); //设置相机方向(指向的场景对象)

  const controls = new OrbitControls(camera, renderer.domElement);

  controls.update();

  const geometry = new BoxGeometry(100, 100, 100);
  const material = new MeshBasicMaterial({ color: 0xff0000 });
  const cube = new Mesh(geometry, material);

  cube.castShadow = true;
  cube.receiveShadow = true;

  scene.add(cube);

  const circleGeometry = new SphereGeometry(60, 40, 40);
  const circleCube = new Mesh(circleGeometry, material);

  circleCube.position.set(200, 0, 0);

  scene.add(circleCube);

  /**
   * 光源设置
   */
  //点光源
  var point = new PointLight(0x666666);
  point.position.set(400, 200, 300); //点光源位置
  scene.add(point); //点光源添加到场景中
  //环境光
  var ambient = new AmbientLight(0x666666);
  scene.add(ambient);

  renderer.setSize(width, height); //设置渲染区域尺寸
  renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色

  // renderer.render( scene, camera );
  function animate() {
    requestAnimationFrame(animate);

    // cube.rotation.x += 0.01;
    // cube.rotation.y += 0.01;
    controls.update();

    renderer.render(scene, camera);
  }

  animate();
});
</script>

<style lang="less" scoped>
.three-box {
  width: 100%;
  height: 100vh;
}
</style>
